using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

using System.Xml;
using System.IO;

using WorkflowProcesses = Scenario.WorkflowEngine.DataModel.WorkflowProcesses;
using WorkflowRelevantData = Scenario.WorkflowEngine.DataModel.WorkflowRelevantData;
using WorkflowParticipantsData = Scenario.WorkflowEngine.DataModel.WorkflowParticipantsData;
using Scenario.WAPI;
using Scenario.WorkflowEngine;

namespace Scenario.Modeler.Forms
{
	/// <summary>
	/// Descrizione di riepilogo per ManageCheck.
	/// </summary>
	public class XSLTFilesManager : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Panel panel1;
		private System.Windows.Forms.Button btnRemove;
		private System.Windows.Forms.Button btnAdd;
		private System.Windows.Forms.ListView listChecks;
		private System.Windows.Forms.Button btnOK;
		/// <summary>
		/// Variabile di progettazione necessaria.
		/// </summary>
		private System.ComponentModel.Container components = null;

		private string sFileManager = string.Empty;
		private System.Windows.Forms.Button btnCheck;
		private string sDirectory = string.Empty;


		//public MainForm MainForm = null;

		public XSLTFilesManager()
		{
			//
			// Necessario per il supporto di Progettazione Windows Form
			//
			InitializeComponent();

			//
			// TODO: aggiungere il codice del costruttore dopo la chiamata a InitializeComponent
			//
		}

		/// <summary>
		/// Pulire le risorse in uso.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Codice generato da Progettazione Windows Form
		/// <summary>
		/// Metodo necessario per il supporto della finestra di progettazione. Non modificare
		/// il contenuto del metodo con l'editor di codice.
		/// </summary>
		private void InitializeComponent()
		{
			this.listChecks = new System.Windows.Forms.ListView();
			this.panel1 = new System.Windows.Forms.Panel();
			this.btnCheck = new System.Windows.Forms.Button();
			this.btnOK = new System.Windows.Forms.Button();
			this.btnRemove = new System.Windows.Forms.Button();
			this.btnAdd = new System.Windows.Forms.Button();
			this.panel1.SuspendLayout();
			this.SuspendLayout();
			// 
			// listChecks
			// 
			this.listChecks.Dock = System.Windows.Forms.DockStyle.Fill;
			this.listChecks.Location = new System.Drawing.Point(0, 0);
			this.listChecks.Name = "listChecks";
			this.listChecks.Size = new System.Drawing.Size(1288, 739);
			this.listChecks.Sorting = System.Windows.Forms.SortOrder.Ascending;
			this.listChecks.TabIndex = 16;
			this.listChecks.View = System.Windows.Forms.View.Details;
			this.listChecks.ItemActivate += new System.EventHandler(this.listChecks_ItemActivate);
			this.listChecks.SelectedIndexChanged += new System.EventHandler(this.listChecks_SelectedIndexChanged);
			// 
			// panel1
			// 
			this.panel1.Controls.Add(this.btnCheck);
			this.panel1.Controls.Add(this.btnOK);
			this.panel1.Controls.Add(this.btnRemove);
			this.panel1.Controls.Add(this.btnAdd);
			this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
			this.panel1.Location = new System.Drawing.Point(0, 659);
			this.panel1.Name = "panel1";
			this.panel1.Size = new System.Drawing.Size(1288, 80);
			this.panel1.TabIndex = 17;
			this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);
			// 
			// btnCheck
			// 
			this.btnCheck.Location = new System.Drawing.Point(456, 24);
			this.btnCheck.Name = "btnCheck";
			this.btnCheck.Size = new System.Drawing.Size(136, 32);
			this.btnCheck.TabIndex = 12;
			this.btnCheck.Text = "Check";
			this.btnCheck.Click += new System.EventHandler(this.btnCheck_Click);
			// 
			// btnOK
			// 
			this.btnOK.Location = new System.Drawing.Point(232, 24);
			this.btnOK.Name = "btnOK";
			this.btnOK.Size = new System.Drawing.Size(200, 32);
			this.btnOK.TabIndex = 11;
			this.btnOK.Text = "OK";
			this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
			// 
			// btnRemove
			// 
			this.btnRemove.Location = new System.Drawing.Point(128, 24);
			this.btnRemove.Name = "btnRemove";
			this.btnRemove.Size = new System.Drawing.Size(88, 40);
			this.btnRemove.TabIndex = 10;
			this.btnRemove.Text = "Remove";
			this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
			// 
			// btnAdd
			// 
			this.btnAdd.Location = new System.Drawing.Point(16, 24);
			this.btnAdd.Name = "btnAdd";
			this.btnAdd.Size = new System.Drawing.Size(88, 40);
			this.btnAdd.TabIndex = 9;
			this.btnAdd.Text = "Add";
			this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
			// 
			// XSLTFilesManager
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
			this.ClientSize = new System.Drawing.Size(1288, 739);
			this.Controls.Add(this.panel1);
			this.Controls.Add(this.listChecks);
			this.Name = "XSLTFilesManager";
			this.Text = "ManageCheck";
			this.Load += new System.EventHandler(this.ManageCheck_Load);
			this.panel1.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		private void panel2_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
		{
		
		}

		private void btnAdd_Click(object sender, System.EventArgs e)
		{
			XSLTFile check = new XSLTFile();
			check.ShowDialog (this);

			if ( check.SaveXSLT ) 
			{
				this.SaveFile (check.txtName.Text, check.txtFileName.Text, check.txtXSLT.Text,check.cmbContexts.Text); 
				ListViewItem item =null;
				item = new ListViewItem( new string[] { check.txtName.Text, check.cmbContexts.Text , check.txtFileName.Text});

				listChecks.Items.Add (item);
			}
		}

		private void ManageCheck_Load(object sender, System.EventArgs e)
		{
			listChecks.Clear();
			listChecks.Columns.Add("Name",listChecks.Width - 200, HorizontalAlignment.Left);
			listChecks.Columns.Add("Context",100, HorizontalAlignment.Left);
			listChecks.Columns.Add("File",100, HorizontalAlignment.Left);

			System.Xml.XmlDocument document = new System.Xml.XmlDocument();

			try
			{
                sDirectory = Engine.FolderHelper.GetFolder(FolderHelper.FolderType.CheckList);
				sFileManager = sDirectory + "\\checkslist.xml";

				document.Load (sFileManager);
				System.Xml.XmlNode root = document.FirstChild;

				System.Xml.XmlNode node;

				for ( int i=0; i<root.ChildNodes.Count;i++)
				{
					node = root.ChildNodes[i];

					ListViewItem item =null;
					item = new ListViewItem( new string[] { node.Attributes["Name"].Value, node.Attributes["Context"].Value , node.Attributes["File"].Value});

					listChecks.Items.Add (item);
				}
			}
			catch (System.Xml.XmlException err)
			{
				System.Console.WriteLine ("Error reading checklist.xml [ {0} ]", err.Message);
			}
		}

		private void btnOK_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void listChecks_SelectedIndexChanged(object sender, System.EventArgs e)
		{
		
		}

		private void listChecks_ItemActivate(object sender, System.EventArgs e)
		{
			XSLTFile check = new XSLTFile();
			check.txtName.Text = listChecks.SelectedItems[0].SubItems[0].Text;
			check.txtName.Enabled = false;

			check.cmbContexts.Text = listChecks.SelectedItems[0].SubItems[1].Text;

			check.txtFileName.Text = listChecks.SelectedItems[0].SubItems[2].Text;
			check.txtFileName.Enabled = false;

			string sFileName = check.txtFileName.Text;
			sFileName+=".xslt";
			FileStream file = new FileStream(this.sDirectory + "\\" + sFileName, FileMode.Open, FileAccess.Read );
			StreamReader w = new StreamReader(file);
			check.txtXSLT.Text = w.ReadToEnd();
			file.Close();

			check.ShowDialog (this);

			if ( check.SaveXSLT )
				this.SaveFile (check.txtName.Text, check.txtFileName.Text, check.txtXSLT.Text,check.cmbContexts.Text); 
		}

		private void SaveFile(string sCheckName, string sFileName, string sXSLT, string sContext)
		{
			FileStream file = new FileStream( sDirectory + "\\" + sFileName + ".xslt", FileMode.Create,FileAccess.Write);
			StreamWriter w = new StreamWriter(file);
			w.Write (sXSLT);
			w.Flush();
			file.Close();

			System.Xml.XmlDocument document = new System.Xml.XmlDocument();
			document.Load (this.sFileManager);
			System.Xml.XmlNode root = document.FirstChild;

			XmlElement elem = null;
			bool bFound = false;
			for ( int i=0; i<root.ChildNodes.Count;i++)
			{
				elem = (XmlElement)root.ChildNodes[i];

				if ( elem.GetAttribute ("Name") == sCheckName )
				{
					bFound = true;
					break;
				}
			}

			if ( bFound ) 
			{
				System.Xml.XmlAttribute attribute = elem.GetAttributeNode("Context");
				attribute.Value = sContext;
			}
			else
			{
				elem = document.CreateElement("Check");
				System.Xml.XmlAttribute attribute = document.CreateAttribute ("Name");
				attribute.Value = sCheckName ;
				elem.Attributes.Append (attribute);

				attribute = document.CreateAttribute("Context");
				attribute.Value = sContext;
				elem.Attributes.Append (attribute);

				attribute = document.CreateAttribute("File");
				attribute.Value = sFileName ;
				elem.Attributes.Append (attribute);

				root.AppendChild (elem);
			}

			document.Save (this.sFileManager);
		}

		private void btnRemove_Click(object sender, System.EventArgs e)
		{
			if ( listChecks.SelectedItems.Count == 0 )
			{
				MessageBox.Show ("almost one check");
				return;
			}

			System.Xml.XmlDocument document = new System.Xml.XmlDocument();
			document.Load (sFileManager);

			System.Xml.XmlNode root = document.FirstChild;
			XmlElement elem = null;
			for ( int i=0; i<root.ChildNodes.Count;i++)
			{
				elem = (XmlElement)root.ChildNodes[i];
				if ( elem.GetAttribute ("Name")  == listChecks.SelectedItems[0].SubItems[0].Text )
				{
					root.RemoveChild (elem);
					try
					{
						System.IO.File.Delete (listChecks.SelectedItems[0].SubItems[2].Text + ".xslt");
					}
					catch 
					{
					}

					listChecks.Items.RemoveAt ( listChecks.SelectedItems[0].Index);
					break;
				}
			}
			document.Save (sFileManager);
		}

		private void btnCheck_Click(object sender, System.EventArgs e)
		{
			if ( listChecks.SelectedItems.Count == 0 )
			{
				MessageBox.Show ("almost one check");
				return;

			}

			XSLTCheck formCheck = new XSLTCheck();
			formCheck.XSLT = this.sDirectory + "\\"  + listChecks.SelectedItems[0].SubItems[2].Text + ".xslt";

			//this.MainForm.BuildModel();

            /*
			WorkflowProcesses.XMLWorkflow xmlWorkflow = null;
			for ( int i=0; i<this.MainForm.xmlWorkflows.Count;i++)
			{
				xmlWorkflow = (WorkflowProcesses.XMLWorkflow )this.MainForm.xmlWorkflows[i];

				formCheck.XML = xmlWorkflow.GetXML();

				formCheck.ShowDialog (this);
			}
            */
			
		}

		private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
		{
		
		}
	}
}
